package com.smm.interceptor;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.util.JSONPObject;
import com.smm.common.Result;
import com.smm.common.ResultCode;
import com.smm.util.JwtUtils;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import org.springframework.util.StringUtils;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;

public class LoginInterceptor extends HandlerInterceptorAdapter {
    Logger log = LoggerFactory.getLogger(LoginInterceptor.class);

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        response.setCharacterEncoding("UTF-8");
        log.info("请求路径:" + request.getRequestURI());
        log.info("请求地址:" + request.getRequestURL());
        log.info("请求方法:" + request.getMethod());
        String authHeader = request.getHeader(JwtUtils.AUTH_HEADER_KEY);
        if (request.getMethod().equals("OPTIONS")) {
            return true;
        }
        if (StringUtils.isEmpty(authHeader) || !authHeader.startsWith(JwtUtils.TOKEN_PREFIX)) {
            log.info("#### 用户未登陆,请登陆 ####");
            //response.getWriter().write(JSON.toJSONString(new Result(ResultCode.USER_NOT_LOGGED_IN)));
            response.getWriter().write(new ObjectMapper().writeValueAsString(new Result(ResultCode.USER_NOT_LOGGED_IN)));
            return false;
        }
        String token = authHeader.substring(7);

        try {

            Claims claims = JwtUtils.parseJwtRS256(token);

        } catch (IOException | NoSuchAlgorithmException | InvalidKeySpecException e) {
            log.error(String.valueOf(e), e);
            response.getWriter().write(JSON.toJSONString(new Result(ResultCode.PERMISSION_TOKEN_INVALID)));
            return false;
        } catch (ExpiredJwtException e) {
            log.error(String.valueOf(e), e);
            response.getWriter().write(JSON.toJSONString(new Result(ResultCode.PERMISSION_TOKEN_EXPIRED)));
            return false;
        }
        return true;

    }
}
